package com.doubao.chat.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.doubao.chat.entity.ChatMessage;
import com.doubao.chat.mapper.ChatMessageMapper;
import com.doubao.chat.service.AIProviderService;
import com.doubao.chat.service.ChatService;
import com.doubao.common.result.Result;
import com.doubao.device.entity.SmartDevice;
import com.doubao.device.service.SmartDeviceService;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;

import java.util.Iterator;
import java.util.Map;

/**
 * 硬件设备API控制器 - 简化版
 * 提供直接的接口，专门用于硬件设备调用AI服务
 */
@RestController
@Slf4j
@Tag(name = "硬件设备API", description = "硬件设备专用接口")
public class HardwareApiController {

    private final ChatService chatService;
    private final SmartDeviceService deviceService;
    private final AIProviderService aiProviderService;
    private final AIProviderService cozeSDKProviderService;
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Autowired // 新增注入
    private ChatMessageMapper messageMapper;

    @Autowired
    public HardwareApiController(
            ChatService chatService,
            SmartDeviceService deviceService,
            @Qualifier("AIProviderServiceImpl") AIProviderService aiProviderService,
            @Qualifier("CozeSDKProviderServiceImpl") AIProviderService cozeSDKProviderService) {
        this.chatService = chatService;
        this.deviceService = deviceService;
        this.aiProviderService = aiProviderService;
        this.cozeSDKProviderService = cozeSDKProviderService;
    }

    /**
     * 简化路径 - 豆包AI(/1)
     */
    @PostMapping("/1")
    @Operation(summary = "豆包AI接口", description = "使用豆包AI回复消息")
    public Result<String> doubaoChat(
            @RequestBody ChatRequest request) {

        log.info("豆包AI接口 - deviceId: {}, 内容: {}", request.getDeviceId(), request.getContent());
        Long providerId = 1L; // 豆包AI

        return chatService.processMessage(0L, request.getDeviceId(), request.getContent());
    }

    /**
     * 简化路径 - 豆包AI - GET请求版本
     */
    @GetMapping("/1/{deviceId}/{content}")
    @Operation(summary = "豆包AI接口-GET版本", description = "使用豆包AI回复消息(GET)")
    public Result<String> doubaoGetChat(
            @PathVariable Long deviceId,
            @PathVariable String content) {

        log.info("豆包AI接口(GET) - deviceId: {}, 内容: {}", deviceId, content);
        Long providerId = 1L; // 豆包AI

        // 使用ChatService处理消息
        return chatService.processMessage(0L, deviceId, content);
    }

    /**
     * 简化路径 - DeepSeek AI(/2)
     */
    @PostMapping("/2")
    @Operation(summary = "DeepSeek AI接口", description = "使用DeepSeek AI回复消息")
    public Result<String> deepseekChat(
            @RequestBody ChatRequest request) {

        log.info("DeepSeek AI接口 - deviceId: {}, 内容: {}", request.getDeviceId(), request.getContent());
        Long providerId = 2L; // DeepSeek AI

        return chatService.processMessage(0L, request.getDeviceId(), request.getContent());
    }

    /**
     * 简化路径 - Dify AI(/3)
     */
    @PostMapping("/3")
    @Operation(summary = "Dify AI接口", description = "使用Dify AI回复消息")
    public Result<String> difyChat(
            @RequestBody BotChatRequest request) {

        log.info("Dify AI接口 - deviceId: {}, botId: {}, 内容: {}",
                request.getDeviceId(), request.getBotId(), request.getContent());
        Long providerId = 3L; // Dify AI

        return chatService.processMessage(0L, request.getDeviceId(), request.getContent());
    }

    /**
     * 简化路径 - 扣子AI(/4)
     */
    @PostMapping("/4")
    @Operation(summary = "扣子AI接口", description = "使用扣子AI回复消息")
    public Result<String> cozeChat(
            @RequestBody BotChatRequest request) {

        log.info("扣子AI接口 - deviceId: {}, botId: {}, 内容: {}",
                request.getDeviceId(), request.getBotId(), request.getContent());
        Long providerId = 4L; // 扣子AI

        // 使用ChatService处理消息，这与前端用户对话的方式相同
        Result<String> result = chatService.processMessage(0L, request.getDeviceId(), request.getContent());

        // 如果不成功，返回错误结果
        if (!result.isSuccess()) {
            return result;
        }

        // 对结果内容进行处理
        String responseData = result.getData();
        if (responseData != null) {
            // 统一处理所有JSON格式响应
            String extractedText = extractTextFromCozeResponse(responseData);

            if (extractedText != null && !extractedText.trim().isEmpty() &&
                !extractedText.equals(responseData)) {
                log.info("从Coze响应中提取文本: {}", extractedText);
                return Result.success(extractedText);
            }

            // 返回处理后的结果
            return Result.success(responseData);
        }

        // 默认返回
        return Result.success("操作成功");
    }

    private String extractTextFromCozeResponse(String jsonResponse) {
        try {
            if (jsonResponse == null || jsonResponse.isEmpty()) {
                return "操作成功";
            }

            // 尝试直接解析为JSON
            JsonNode rootNode = objectMapper.readTree(jsonResponse);

            // 优先检查嵌套的data字段
            // 深度遍历整个JSON结构
            String result = deepSearchTextNodes(rootNode);

            // 如果未找到有效文本，尝试原始data字段
            if (!StringUtils.hasText(result) && rootNode.has("data")) {
                JsonNode dataNode = rootNode.get("data");
                if (dataNode.isTextual()) {
                    return dataNode.asText();
                }
                result = deepSearchTextNodes(dataNode);
            }

            if (StringUtils.hasText(result)) {
                return result;
            }

            // 保留原始响应作为兜底方案
            return jsonResponse;
        } catch (Exception e) {
            log.error("解析扣子AI响应JSON异常: {}", e.getMessage());
            return jsonResponse;
        }
    }

    private String deepSearchTextNodes(JsonNode node) {
        if (node.isObject()) {
            Iterator<Map.Entry<String, JsonNode>> fields = node.fields();
            while (fields.hasNext()) {
                Map.Entry<String, JsonNode> entry = fields.next();
                String key = entry.getKey().toLowerCase();
                JsonNode value = entry.getValue();

                // 优先检查高优先级字段
                if (key.equals("content") || key.equals("text") || key.equals("answer")) {
                    if (value.isTextual()) {
                        return value.asText();
                    }
                }

                // 递归搜索嵌套结构
                String nestedResult = deepSearchTextNodes(value);
                if (nestedResult != null) {
                    return nestedResult;
                }
            }
        } else if (node.isArray()) {
            for (JsonNode element : node) {
                String nestedResult = deepSearchTextNodes(element);
                if (nestedResult != null) {
                    return nestedResult;
                }
            }
        }
        return null;
    }

    /**
     * 标准消息发送接口(同时处理JSON和表单请求)
     */
    @PostMapping("/chat")
    @Operation(summary = "发送消息", description = "硬件设备发送消息并获取AI回复")
    public Result<String> sendMessage(
            @RequestParam(value = "userId", required = false) Long userId,
            @RequestParam("deviceId") @NotNull Long deviceId,
            @RequestParam("content") @NotBlank String content,
            @RequestParam(value = "providerId", required = false) Long providerId) {

        log.info("硬件设备发送消息 - userId: {}, deviceId: {}, providerId: {}, content长度: {}",
                userId, deviceId, providerId, content.length());

        if (providerId != null) {
            // 对于特殊提供商，需要额外处理
            if (providerId == 3 || providerId == 4) {
                // Dify AI或扣子AI需要botId
                SmartDevice device = deviceService.getById(deviceId);
                if (device != null) {
                    return directCallWithBotId(userId, deviceId, providerId, device.getAiModelId(), content);
                }
            }
            return processMessageWithProvider(userId, deviceId, providerId, content);
        } else {
            return chatService.processMessage(userId, deviceId, content);
        }
    }

    /**
     * 通用JSON消息发送接口
     */
    @PostMapping("/chat/json")
    @Operation(summary = "发送消息(JSON)", description = "硬件设备通过JSON发送消息并获取AI回复")
    public Result<String> sendMessageJson(
            @RequestHeader(value = "X-User-ID", required = false) Long userId,
            @RequestBody HardwareChatRequest request) {

        log.info("硬件设备发送JSON消息 - userId: {}, deviceId: {}, content长度: {}, 提供商ID: {}",
                userId, request.getDeviceId(), request.getContent().length(), request.getProviderId());

        if (request.getProviderId() != null) {
            // 对于特殊提供商，需要额外处理
            if (request.getProviderId() == 3 || request.getProviderId() == 4) {
                // Dify AI或扣子AI需要botId
                SmartDevice device = deviceService.getById(request.getDeviceId());
                if (device != null) {
                    return directCallWithBotId(userId, request.getDeviceId(), request.getProviderId(),
                            device.getAiModelId(), request.getContent());
                }
            }
            return processMessageWithProvider(userId, request.getDeviceId(), request.getProviderId(), request.getContent());
        } else {
            return chatService.processMessage(userId, request.getDeviceId(), request.getContent());
        }
    }

    /**
     * 使用指定提供商处理消息
     */
    private Result<String> processMessageWithProvider(Long userId, Long deviceId, Long providerId, String content) {
        try {
            // 如果指定了提供商ID，则更新设备的提供商ID
            if (providerId != null) {
                try {
                    SmartDevice device = deviceService.getById(deviceId);
                    if (device != null && !providerId.equals(device.getAiProviderId())) {
                        log.info("临时切换设备提供商 - deviceId: {}, 原提供商: {}, 新提供商: {}",
                                deviceId, device.getAiProviderId(), providerId);
                        // 临时修改设备的提供商ID
                        device.setAiProviderId(providerId);
                    }
                } catch (Exception e) {
                    log.warn("获取设备信息失败", e);
                }
            }

            // 调用服务处理消息
            return chatService.processMessage(userId, deviceId, content);
        } catch (Exception e) {
            log.error("处理消息异常", e);
            return Result.failed("处理消息异常: " + e.getMessage());
        }
    }

    /**
     * 使用指定的botId直接调用AI
     */
    private Result<String> directCallWithBotId(Long userId, Long deviceId, Long providerId, String botId, String content) {
        try {
            // 获取设备信息
            SmartDevice device = deviceService.getById(deviceId);
            if (device == null) {
                return Result.failed("设备不存在");
            }

            // 设置botId
            if (botId != null) {
                device.setAiModelId(botId);
                log.info("临时设置botId: {}", botId);
            }

            // 设置提供商ID
            if (providerId != null) {
                device.setAiProviderId(providerId);
            }

            // 获取系统提示词
            Result<String> promptResult;
            if (providerId != null && providerId == 4) { // 扣子AI
                promptResult = cozeSDKProviderService.getSystemPrompt(deviceId);
            } else {
                promptResult = aiProviderService.getSystemPrompt(deviceId);
            }
            String systemPrompt = promptResult.isSuccess() ? promptResult.getData() : "";

            // 直接调用AI提供商
            Result<String> aiResponse;
            if (providerId != null && providerId == 4) { // 扣子AI
                aiResponse = cozeSDKProviderService.sendMessageToProvider(
                        deviceId, systemPrompt, null, content);
            } else {
                aiResponse = aiProviderService.sendMessageToProvider(
                        deviceId, systemPrompt, null, content);
            }

            return aiResponse;
        } catch (Exception e) {
            log.error("直接调用AI异常", e);
            return Result.failed("调用AI异常: " + e.getMessage());
        }
    }

    /**
     * 基础聊天请求
     */
    @lombok.Data
    public static class ChatRequest {
        private Long deviceId;
        private String content;
    }

    /**
     * 带botId的聊天请求
     */
    @lombok.Data
    public static class BotChatRequest {
        private Long deviceId;
        private String content;
        private Long botId;
    }

    /**
     * 标准聊天请求
     */
    @lombok.Data
    public static class HardwareChatRequest {
        private Long deviceId;
        private String content;
        private Long providerId;
    }
}